package com.lc.aiagent.advisor;

import com.lc.aiagent.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.advisor.api.*;
import org.springframework.ai.chat.model.MessageAggregator;
import reactor.core.publisher.Flux;

@Slf4j
public class PermissionCheckAdvisor implements CallAroundAdvisor, StreamAroundAdvisor {

    // 权限校验服务
    private final PermissionService permissionService;

    public PermissionCheckAdvisor(PermissionService permissionService) {
        this.permissionService = permissionService;
    }

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    @Override
    public int getOrder() {
        // 权限校验应在最前面执行
        return HIGHEST_PRECEDENCE;
    }

    private AdvisedRequest before(AdvisedRequest request) {
        // 从请求中提取权限信息
        // String userId = request.getUser().getId();
        // String operation = request.getOperationType();
        
        // if (!permissionService.checkPermission(userId, operation)) {
        //     throw new SecurityException("用户 " + userId + " 无权限执行操作: " + operation);
        // }
        return request;
    }

    @Override
    public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) {
        advisedRequest = before(advisedRequest);
        return chain.nextAroundCall(advisedRequest);
    }

    @Override
    public Flux<AdvisedResponse> aroundStream(AdvisedRequest advisedRequest, StreamAroundAdvisorChain chain) {
        advisedRequest = before(advisedRequest);
        return chain.nextAroundStream(advisedRequest);
    }
}